/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.cheetah.youbet.gui.component;

import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBox;
import javax.swing.JRadioButton;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;
import org.apache.commons.lang3.RandomStringUtils;
import org.cheetah.youbet.ContextSpringFactory;
import org.cheetah.youbet.bean.Bolletta;
import org.cheetah.youbet.entities.Classe;
import org.cheetah.youbet.entities.Palinsesto;
import org.cheetah.youbet.entities.Quota;
import org.cheetah.youbet.gui.BollettaDaGiocareDialog;
import org.cheetah.youbet.gui.editor.QuotaTableCellEditor;
import org.cheetah.youbet.gui.model.QuotaTableModel;
import org.cheetah.youbet.service.GenericService;
import org.springframework.beans.BeansException;

/**
 *
 * @author edoardo
 */
public class PanelClassiRadioButton extends javax.swing.JPanel {

    private static final int DEFAULT_ELEMENTS_PER_ROW = 3;

    private int elementsPerRow = DEFAULT_ELEMENTS_PER_ROW;
    private Palinsesto palinsesto;

    /**
     * Creates new form DynamicPanelRadioButton
     */
    public PanelClassiRadioButton(List<Classe> classes, int elementsPerRows, Palinsesto palinsesto) {
        this.elementsPerRow = elementsPerRows;
        this.palinsesto = palinsesto;
        initComponents();
        addRadio(classes);
    }

    public PanelClassiRadioButton(List<Classe> classes, Palinsesto palinsesto) {
        this(classes, DEFAULT_ELEMENTS_PER_ROW, palinsesto);
    }

    public PanelClassiRadioButton() {
        this(new ArrayList<Classe>(), DEFAULT_ELEMENTS_PER_ROW, new Palinsesto());
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        panelRadioButton = new javax.swing.JPanel();
        panelQuotaTable = new javax.swing.JPanel();
        scrollPaneQuota = new javax.swing.JScrollPane();
        tableQuota = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        buttonVediBolletta = new javax.swing.JButton();

        setLayout(new java.awt.GridBagLayout());

        panelRadioButton.setLayout(new java.awt.GridBagLayout());
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 0.5;
        add(panelRadioButton, gridBagConstraints);

        panelQuotaTable.setLayout(new java.awt.GridBagLayout());

        tableQuota.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {},
            new String [] {}
        ));
        scrollPaneQuota.setViewportView(tableQuota);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        panelQuotaTable.add(scrollPaneQuota, gridBagConstraints);

        buttonVediBolletta.setText("Vedi bolletta");
        buttonVediBolletta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonVediBollettaActionPerformed(evt);
            }
        });
        jPanel1.add(buttonVediBolletta);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        panelQuotaTable.add(jPanel1, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 0.5;
        add(panelQuotaTable, gridBagConstraints);
    }// </editor-fold>//GEN-END:initComponents

    private void buttonVediBollettaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonVediBollettaActionPerformed
        BollettaDaGiocareDialog b = ContextSpringFactory.getInstance().getContext().getBean(BollettaDaGiocareDialog.class);
        if (!b.isShowing()) {
            b.setVisible(true);
        }
        b.setBolletta(getBolletta());
        b.getTableGiocata().setModel(b.createModel());

        // TODO add your handling code here:
    }//GEN-LAST:event_buttonVediBollettaActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonVediBolletta;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel panelQuotaTable;
    private javax.swing.JPanel panelRadioButton;
    private javax.swing.JScrollPane scrollPaneQuota;
    private javax.swing.JTable tableQuota;
    // End of variables declaration//GEN-END:variables
    private void addRadio(List<Classe> classes) {
        ButtonGroup buttonGroup = new ButtonGroup();
        GridBagConstraints gbc = null;
        int x = 0;
        int y = 0;
        int counter = 0;
        Map<String, QuotaTableModel> modelsMap = new HashMap<String, QuotaTableModel>();
        //per non avere problemi quando viene selezionata/deselezionata la quota, memorizzo le checkbox
        final Map<String, List<JCheckBox>> checkBoxesContainer = new HashMap<String, List<JCheckBox>>();
        for (int i = 0; i < classes.size(); i++) {
            JRadioButton jRadioButton1 = new javax.swing.JRadioButton();

            jRadioButton1.setText(classes.get(i).getDescrizione());
            jRadioButton1.setName(Integer.toString(classes.get(i).getIdClasse()));

            int idClasse = Integer.parseInt(Integer.toString(classes.get(i).getIdClasse()));
            GenericService ser = ContextSpringFactory.getInstance().getContext().getBean(GenericService.class);
            final List<Quota> visibleQuota = ser.findQuotaByPalinsestoAndClasse(palinsesto, idClasse);
            QuotaTableModel model = new QuotaTableModel(visibleQuota);
            model.setVisibleColumns(new QuotaTableModel.QuotaColumn[]{
                QuotaTableModel.QuotaColumn.RADIO_BUTTON_OBJECT,
                QuotaTableModel.QuotaColumn.DESCRIZIONE_ESITO,
                QuotaTableModel.QuotaColumn.QUOTA
            });

            modelsMap.put(Integer.toString(classes.get(i).getIdClasse()), model);
            final Map _amap_ = modelsMap;
            jRadioButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    final JRadioButton radio = (JRadioButton) evt.getSource();
                    //qui va preso il model per il radio button
                    final QuotaTableModel _model_ = (QuotaTableModel) _amap_.get(radio.getName());
                    tableQuota.setModel(_model_);
                    List<JCheckBox> checkBoxs = checkBoxesContainer.get(radio.getName());
                    if (checkBoxs == null) {
                        checkBoxs = new ArrayList<JCheckBox>();
                        for (Quota quota : visibleQuota) {
                            JCheckBox chk = null;
                            checkBoxs.add(chk = new JCheckBox());
                            chk.setName(RandomStringUtils.randomAlphabetic(6));
                        }
                        checkBoxesContainer.put(radio.getName(), checkBoxs);
                    }
                    final List<JCheckBox> _check_ = checkBoxs;
                    tableQuota.getColumnModel().getColumn(0).setCellRenderer(new TableCellRenderer() {
                        public Component getTableCellRendererComponent(final JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                            boolean marked = (Boolean) value;
                            JCheckBox rendererComponent = _check_.get(row);

                            rendererComponent.addItemListener(new ItemListener() {

                                public void itemStateChanged(ItemEvent e) {
                                    Bolletta bolletta = getBolletta();
                                    if (table.getSelectedRow() > -1) {
                                        Quota quotaSelected
                                                = ((QuotaTableModel) table.getModel()).
                                                getQuotas().
                                                get(table.getSelectedRow());
                                        if (((JCheckBox) e.getSource()).isSelected()) {

                                            bolletta.confirmGiocata(quotaSelected);
                                            bolletta.addGiocata(palinsesto, quotaSelected);
                                        } else {
                                            bolletta.cancelGiocata(
                                                    ((QuotaTableModel) table.getModel()).
                                                    getQuotas().
                                                    get(table.getSelectedRow()));
                                            bolletta.removeGiocata(palinsesto, quotaSelected);
                                        }
                                    }

                                }
                            });
                            table.getColumnModel().getColumn(0).setCellEditor(new QuotaTableCellEditor(rendererComponent));
                            if ((Boolean) value) {
                                System.out.println("Checkbox name: " + rendererComponent.getName());
                                rendererComponent.setSelected(true);
                            }
//                            for (int r = 0; r < ((QuotaTableModel) tableQuota.getModel()).getQuotas().size(); r++) {
//                                Quota quota = ((QuotaTableModel) tableQuota.getModel()).getQuotas().get(r);
//                                if (getBolletta().getGiocata().get(quota.getPalinsesto()) != null && getBolletta().getGiocata().get(quota.getPalinsesto()).contains(quota)) {
//                                    rendererComponent.setSelected(true);
//
//                                }
//                            }
                            return rendererComponent;
                        }
                    });
//                    tableQuota.getColumnModel().getColumn(0).setCellEditor(new QuotaTableCellEditor(new JCheckBox()));
                    _model_.fireTableDataChanged();

                }
            });
            gbc = new GridBagConstraints();
            gbc.gridx = x;
            gbc.gridy = y;
            gbc.gridwidth = 1;
            gbc.gridheight = 1;
            gbc.anchor = GridBagConstraints.WEST;
            gbc.insets.bottom = 5;
            gbc.insets.top = 5;
            gbc.insets.left = 10;
            gbc.insets.right = 10;
            gbc.weightx = 100.0 / Double.parseDouble(Integer.toString(elementsPerRow));
            System.out.println(gbc.gridx + "," + gbc.gridy);
            panelRadioButton.add(jRadioButton1, gbc);
            counter = counter + 1;
            x = x + 1;
            if (counter >= elementsPerRow) {
                x = 0;
                y = y + 1;
                counter = 0;
            }
            buttonGroup.add(jRadioButton1);
        }
        repaint();
    }

    private Bolletta getBolletta() throws BeansException {
        Bolletta bolletta = ContextSpringFactory.getInstance()
                .getContext()
                .getBean(Bolletta.class);
        return bolletta;
    }
}
